<template>
  <el-card class="card">
    <div slot="header">
      <span>报修</span>
    </div>
    <div>
      <div class="title"><img src="@/assets/repair.png" class="title-icon"><span class="title-text">报修内容：</span></div>
      <el-checkbox-group v-model="checkList" @change="checkListChange">
        <el-checkbox v-for="(item,index) in checkboxList" :key="index" :label="item">{{ item.keyName }}</el-checkbox>
      </el-checkbox-group>
      <el-input v-model="form.repairContent" class="textarea" type="textarea" :rows="3" placeholder="请输入内容" />
      <div v-if="(currentAppointment.length>0)" class="appointment-row">
        <div>预约时间:</div>
        <p class="timeContent" @click="showAppointment">
          <span v-if="!currentDayContent" class="placeholder">请选择预约时间</span>
          <span v-else>{{ currentDayContent }}</span>
        </p>
      </div>
      <div class="appointment">

        <el-card v-if="popoverVisible" class="appointment-warp">
          <div class="head">
            <div v-for="(item,index) in currentAppointment" :key="index" :class="currentDayInfo.day===item.appointmentDate?'appointment':''" @click="selectAppointment(item, index)">
              <span v-if="index===0">今天</span>
              <span v-if="index===1">明天</span>
              <span v-if="index===2">后天</span>
              <span>{{ item.appointmentDate }}</span>
            </div>
          </div>
          <div class="content">
            <div v-for="(item, idx) in currentAppointment[parentIndex].appointmentTimeList" :key="idx" class="content-item">
              <div class="time-item">
                <p @click="selectTimePart(item,idx)">
                  <span :class="item.select?'time-active':''">{{ (parentIndex===0&&item.showIndex===0)?item.title: item.startTime+'~'+item.endTime }}</span>
                </p>
              </div>
            </div>
            <p v-if="currentAppointment[parentIndex].appointmentTimeList.length===0" class="noAppointmentList">暂无可选时间段</p>
          </div>
          <div class="foot">
            <el-button size="mini" @click="popoverVisible = false">取 消</el-button>
            <el-button size="mini" type="primary" @click="confirmed">确 定</el-button>
          </div>
        </el-card>
      </div>
      <div class="title-table">最近三次报修记录：</div>
      <el-table :height="165" :data="tableData">
        <el-table-column prop="repairCode" label="报修单号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="answer" label="登记人" min-width="90" show-overflow-tooltip />
        <el-table-column prop="createTime" label="登记时间" min-width="140" show-overflow-tooltip />
        <el-table-column prop="repairContent" label="报修内容" min-width="170" show-overflow-tooltip />
        <el-table-column prop="statusName" label="状态" min-width="80" show-overflow-tooltip />
        <el-table-column label="催单" min-width="80" show-overflow-tooltip>
          <template slot-scope="{row}">
            <el-button v-if="row.statusName === '已审待处理'" type="text" class="btnText" @click="handleReminder(row)">催单</el-button>
            <span v-else>催单</span>
          </template>
        </el-table-column>
        <el-table-column label="退单" min-width="80" show-overflow-tooltip>
          <template slot-scope="{row}">
            <el-button v-if="row.statusName === '已审待处理'" type="text" class="btnText" @click="handleChargeback(row)">退单</el-button>
            <span v-else>退单</span>
          </template>
        </el-table-column>
        <el-table-column label="流转" min-width="90" show-overflow-tooltip>
          <template slot-scope="{row}">
            <el-button type="text" class="btnText" @click="handleExchange(row)">流转</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        :loading="$loadingPlugin.submit"
        type="primary"
        class="submitBtn"
        @click="submit"
      >提交报修登记</el-button>
    </div>
    <reminderDialog ref="reminderDialog" type="repair" :client-selected="clientSelected" />
    <chargebackDialog ref="chargebackDialog" type="repair" @chargebackSubmit="chargebackSubmit" />
    <exchangeDialog ref="exchangeDialog" :client-selected="clientSelected" />
  </el-card>
</template>

<script>
  import reminderDialog from './reminderDialog.vue'
  import chargebackDialog from './chargebackDialog.vue'
  import exchangeDialog from './exchangeDialog.vue'
  import { parseTime } from '@/utils'
  import dayjs from 'dayjs'
  import { repairTop, repairSearch, repairSave, repairCommonkeys, repairAppointmentList } from '@/api'
  export default {
    name: 'call-repair',
    components: { reminderDialog, chargebackDialog, exchangeDialog },
    props: {
      temp: {
        type: Object,
        default: () => { return {} }
      },
      userData: {
        type: Object,
        default: () => { return {} }
      },
      currentPhoneData: {
        type: Object,
        default: () => { return {} }
      }
    },
    data() {
      return {
        checkboxList: [],
        checkList: [],
        form: {
          repairContent: ''
        },
        tableData: [],
        clientSelected: {},
        isOnSubmit: false,
        shippingAddress: {},
        currentDayContent: '',
        popoverVisible: false,
        currentAppointment: [],
        parentIndex: 0,
        currentDayInfo: {},
        confirmedDayInfo: {}
      }
    },
    created() {
      this.repairSearch()
      this.getRepairCommonkeys()
    },
    methods: {
      async repairSearch() {
        const res = await repairSearch()
        this.repairStatus = JSON.parse(res.data.repairStatus)
      },
      async getRepairTop(clientSelected, shippingAddress) {
        this.tableData = []
        this.clientSelected = clientSelected
        if (clientSelected.csmId) {
          this.shippingAddress = shippingAddress
          const params = {
            csmId: clientSelected.csmId,
            topCount: 3
            // corpSN: clientSelected.corpSN
          }
          const res = await repairTop(params)
          if (res.data) {
            this.tableData = res.data
            this.tableData.forEach((item) => {
              const status = this.repairStatus.filter((item2) => {
                return item2.value === item.rstatus
              })
              if (status.length > 0) {
                item.statusName = status[0].desc
              }
              item.createTime = item.createTime ? parseTime(item.createTime) : ''
              item.createTime = item.createTime ? dayjs(item.createTime).format('YY-MM-DD HH:mm') : ''
            })
          }
        }
      },
      checkListChange() {
        if (this.checkList.length > 0) {
          const c = this.checkList.filter(item => (item.sp1 & 0x01) === 1)
          console.log(c)
          if (c && c.length > 0 && this.currentAppointment.length > 0) {
            this.confirmedDayInfo.day = parseTime(new Date(), '{y}-{m}-{d}')
            this.confirmedDayInfo.time = this.currentAppointment[0].appointmentTimeList[0]
            this.currentDayContent = this.confirmedDayInfo.time.title
          } else {
            this.confirmedDayInfo = {}
            this.currentDayContent = ''
          }
        } else {
          this.confirmedDayInfo = {}
          this.currentDayContent = ''
        }
      },

      async getRepairCommonkeys() {
        const params = {
          keyFun: 2,
          keyAttr: 1
        }
        const res = await repairCommonkeys(params)
        if (res && res.data) {
          this.checkboxList = res.data
        }
      },
      // 催单
      async handleReminder(row) {
        await this.$refs.reminderDialog.open(row)
      },
      // 退单
      async handleChargeback(row) {
        await this.$refs.chargebackDialog.open(row)
      },
      // 流转
      async handleExchange(row) {
        await this.$refs.exchangeDialog.open(row, 'repair')
      },
      chargebackSubmit() {
        this.getRepairTop(this.clientSelected, this.shippingAddress)
      },
      async submit() {
        // if (!this.userData.userId) {
        //   this.$message.error('提交失败！此机构无调度员')
        //   return
        // }
        if (!(this.clientSelected && this.clientSelected.csmCode)) {
          this.$message.error('请选择客户信息后操作')
          return
        }
        let repairContent = ''
        if (this.checkList.length > 0) {
          const c = this.checkList.map((item) => (item.keyName))
          repairContent = c.join(';')
        }
        // if (this.form.repairContent) {
        //   repairContent = repairContent ? repairContent + ';' + this.form.repairContent : this.form.repairContent
        // }
        if (!repairContent) {
          this.$message.error('请输入报修内容')
          return
        }
        if (repairContent.length > 200) {
          this.$message.error('报修内容太长')
          return
        }
        if ((!(this.confirmedDayInfo.day && this.confirmedDayInfo.time && this.confirmedDayInfo.time.startTime)) && this.currentAppointment.length > 0) {
          this.$message.error('请选择预约时间')
          return
        }
        const param = JSON.parse(JSON.stringify(this.clientSelected))
        param.repairContent = repairContent
        param.contactPhone = param.csmRgPhone
        param.contact = this.temp.contactName
        param.contactAddressId = this.shippingAddress.csmAddressId
        param.callPhone = param.csmRgPhone
        param.csmOrgId = param.nearStation
        param.csmOrgSNNo = param.orgSNNo
        param.csmOrgName = param.nearStationName
        param.csmAddress = this.shippingAddress.provinceName + this.shippingAddress.cityName + this.shippingAddress.countryName + this.shippingAddress.csmAddress
        param.contactAddress = this.shippingAddress.provinceName + this.shippingAddress.cityName + this.shippingAddress.countryName + this.shippingAddress.csmAddress
        param.userName = this.temp.userId ? this.temp.userName : ''
        param.userCode = this.temp.userId ? this.temp.userCode : ''
        param.userId = this.temp.userId
        param.fromPlat = 1
        param.dueTime = new Date()
        // param.corpSN = this.clientSelected.corpSN
        param.callCode = this.currentPhoneData.sn || ''
        param.orgId = this.userData.orgId || this.temp.orgId
        param.orgName = this.userData.orgName || this.temp.orgName
        param.orgSNNo = this.userData.orgSNNo || this.temp.orgSNNo
        if (this.confirmedDayInfo.day && this.confirmedDayInfo.time && this.confirmedDayInfo.time.startTime) {
          param.appointmentStartTime = this.confirmedDayInfo.day + ' ' + this.confirmedDayInfo.time.startTime + ':00'
          param.appointmentEndTime = this.confirmedDayInfo.day + ' ' + this.confirmedDayInfo.time.endTime + ':00'
        }
        param.remark = this.form.repairContent
        this.isOnSubmit = true

        // repairSave(query).then(res => {
        //   if (res.data) {
        //     this.$message.success('操作成功')
        //     this.isOnSubmit = false
        //     this.form.repairContent = ''
        //     this.checkList = []
        //     this.tableData = []
        //     this.currentDayContent = ''
        //     this.currentAppointment = []
        //     this.currentDayInfo = {}
        //     this.$emit('onSubmit')
        //   }
        // })
        console.log(param)
        const res = await repairSave(param)
        if (res && res.data) {
          this.$message.success('操作成功')
          this.isOnSubmit = false
          this.form.repairContent = ''
          this.checkList = []
          this.tableData = []
          this.resetAppointment()
          this.temp.userId = ''
          this.temp.userName = ''
          this.$emit('onSubmit')
        }
      },
      async getAppointmentData(orgId) {
        const params = {
          appointmentDt: dayjs(new Date()).format('YYYY-MM-DD') + ' ' + '00:00:00',
          orgId
        }
        const res = await repairAppointmentList(params)
        if (res && res.data && res.data.length > 0) {
          this.currentAppointment = res.data
        }
      },
      resetAppointment() {
        this.currentDayContent = ''
        this.parentIndex = 0
        this.currentAppointment = []
        this.currentDayInfo = {}
        this.confirmedDayInfo = {}
      },
      async showAppointment() {
        if (this.currentAppointment && this.currentAppointment.length > 0) {
          this.currentDayInfo.day = parseTime(new Date(), '{y}-{m}-{d}')
          // this.selectTimePart(this.currentAppointment[this.parentIndex].appointmentTimeList[0], 0)
          this.popoverVisible = !this.popoverVisible
          if (this.confirmedDayInfo && this.confirmedDayInfo.day) {
            this.resetCurrentAppointment()
            this.currentDayInfo.day = this.confirmedDayInfo.day
            const c_item = this.currentAppointment[this.parentIndex].appointmentTimeList.findIndex(item => item.startTime === this.confirmedDayInfo.time.startTime)
            if (c_item) {
              this.currentAppointment[this.parentIndex].appointmentTimeList[c_item].select = true
            } else {
              this.currentAppointment[this.parentIndex].appointmentTimeList[0].select = true
            }
            this.currentDayInfo.time = this.confirmedDayInfo.time
          }
        } else {
          this.$message.warning('暂无可选时间段')
        }
      },
      confirmed() {
        console.log(this.currentDayInfo)
        if (!(this.currentDayInfo.time && this.currentDayInfo.time.startTime)) {
          this.$message.warning('请先选择时间段')
          return
        }
        this.currentDayContent = this.currentDayInfo.day + '  ' + this.currentDayInfo.time.startTime + '~' + this.currentDayInfo.time.endTime
        if (this.parentIndex === 0 && this.currentDayInfo.time.showIndex === 0) {
          this.currentDayContent = this.currentDayInfo.time.title
        }
        this.confirmedDayInfo = JSON.parse(JSON.stringify(this.currentDayInfo))
        this.popoverVisible = false
      },
      // 选中天
      async selectAppointment(val, index) {
        this.parentIndex = index
        this.currentDayInfo.day = val.appointmentDate
        this.currentDayInfo.time = null
        this.resetCurrentAppointment()
        // this.selectTimePart(this.currentAppointment[this.parentIndex].appointmentTimeList[0], 0)
      },
      // 选中时间段
      selectTimePart(val, index) {
        console.log(val, index)
        this.resetCurrentAppointment()
        this.currentAppointment[this.parentIndex].appointmentTimeList[index].select = true
        this.currentDayInfo.time = val
      },
      resetCurrentAppointment() {
        this.currentAppointment[this.parentIndex].appointmentTimeList = this.currentAppointment[this.parentIndex].appointmentTimeList.map((item, idx) => ({
          ...item,
          select: false
        }))
      }
    }
  }
</script>

<style lang="scss" scoped>
.card {
  border-radius: 8px;
  & /deep/ .el-card__header {
    padding-bottom: 10px;
    padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  & /deep/ .el-card__body {
    min-height: 100px;
    padding: 10px;
    .title {
      margin: 10px 0 5px;
      font-size: 16px;
      font-weight: 600;
      color: #ED912E;
      .title-icon {
        position: relative;
        right: 3px;
        width: 20px;
      }
      .title-text {
        position: relative;
        top: -5px;
      }
    }
    .textarea {
      margin-top: 15px;
    }
    .title-table {
      margin: 15px 0;
      font-size: 16px;
      font-weight: 600;
      color: #F56C6C;
    }
    .submitBtn {
      float: right;
      margin: 10px 0;
    }
    .btnText {
      font-size: 14px;
    }
  }
}

.appointment {
  position: relative;
  width: 380px;
  cursor: pointer;
}
.appointment-row {
  display: flex;
  align-items: center;
  margin-top: 10px;
  div {
    min-width: 70px;
    font-size: 14px;
    font-weight: 600;
  }
}
.timeContent {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 300px;
  line-height: 36px;
  cursor: pointer;
  border-bottom: 1px solid #dcdfe6;
  .placeholder {
    color: #c0c4cc;
  }
  img {
    width: 24px;
    height: 24px;
  }
}

.appointment-warp {
  position: absolute;
  bottom: -6px;
  left: 374px;
  z-index: 999;
  width: 380px;
  .head {
    display: flex;
    align-items: center;
    div {
      text-align: center;
      cursor: pointer;
      flex: 1;
      span {
        display: block;
        line-height: 20px;
      }
      &:hover {
        background: #EBEEF5;
      }
    }
    .appointment {
      color: $themeColor;
    }
    i {
      font-size: 24px;
    }
  }
  .content {
    display: flex;
    justify-content: flex-start;
    max-height: 120px;
    min-height: 100px;
    margin: 10px 0;
    overflow-y: auto;
    // align-items: center;
    flex-wrap: wrap;
    .content-item {
      width: 110px;
      margin-bottom: 2px;
      .time-item {
        padding-left: 2px;

        p {
          text-align: center;
          cursor: pointer;
          flex: 1;
          span {
            display: block;
            line-height: 28px;
          }
          .dis {
            color: red;
          }
          &:hover {
            background: #EBEEF5;
          }
        }
        .p-disabel-gray {
          span:nth-child(1) {
            color: #c0c4cc;
          }
        }
        .time-active {
          color: $themeColor;
          background-color: rgba(19, 177, 177, 0.2);
        }
      }
    }
    .noAppointmentList {
      margin-left: 125px;
      font-size: 14px;
      color: #c0c4cc;
      align-self: center;
    }
  }
  .foot {
    text-align: right;
  }
}

</style>
